package com.cvte.shop.config;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.stereotype.Component;

/**
 * @author DaiShubo
 * @version 1.0
 * @description 日志配置类
 * @createTime 2020/8/3 10:41 上午
 * @since 1.7
 **/
@Component
@Slf4j
public class LogConfig {

    private final static String LOGGER_PREFIX="logging.level.";

    @Autowired
    private LoggingSystem loggingSystem;


    @ApolloConfigChangeListener
    private void configChangeListter(ConfigChangeEvent changeEvent){

        //监听配置中心日志
        changeEvent.changedKeys().stream().forEach(key -> {

            ConfigChange change = changeEvent.getChange(key);

            if(StringUtils.containsIgnoreCase(key, LOGGER_PREFIX)) {
                loggingSystem.setLogLevel(key.replace(LOGGER_PREFIX, ""), LogLevel.valueOf(change.getNewValue().toUpperCase()));
            }

            log.info("【apollo】 change {} config from {} to {}", key, change.getOldValue(), change.getNewValue());
        });

    }
}
